package com.github.ilioili.justdoit.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;

/**
 * Created by hantuo on 16/5/25.
 */
public class ScrollPage extends LinearLayout implements ValueAnimator.AnimatorUpdateListener {

    private ValueAnimator valueAnimator;

    public ScrollPage(Context context) {
        this(context, null);
    }

    public ScrollPage(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScrollPage(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        valueAnimator = new ValueAnimator();
        valueAnimator.setDuration(300);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.addUpdateListener(this);
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                for (int i = 0; i < getChildCount(); i++) {
                    getChildAt(i).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                int currentShowChildIndex = getCurrentPageIndex();
                for (int i = 0; i < getChildCount(); i++) {
                    if (currentShowChildIndex != i) {
                        getChildAt(i).setVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    public int getCurrentPageIndex() {
        return 0 == getMeasuredHeight() ? 0 : (getScrollY() + 1) / getMeasuredHeight();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ScrollPage(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
    }

    public void scrollToPage(int index) {
        if (valueAnimator.isRunning()) {
            valueAnimator.cancel();
        }
        valueAnimator.setIntValues(getScrollY(), index * getMeasuredHeight());
        valueAnimator.start();
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        scrollTo(0, (Integer) animation.getAnimatedValue());
    }
}
